package cn.flant.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtil {
	private static DateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final long SECOND = 1000L;
	public static final long MINUTES = SECOND * 60;
	public static final long HOUR = MINUTES * 60;
	public static final long DAY = HOUR * 24;

	public static String format(Date date) {
		synchronized (formatDateTime) {
			return formatDateTime.format(date);
		}
	}

	public static String format(Date date, String format) {
		return new SimpleDateFormat(format).format(date);
	}

	public static Date parse(String datetime) {
		synchronized (formatDateTime) {
			try {
				return formatDateTime.parse(datetime);
			} catch (Exception e) {
				return null;
			}
		}
	}

	public static Date parse(String datetime, String parse) {
		try {
			return new SimpleDateFormat(parse).parse(datetime);
		} catch (Exception e) {
			return null;
		}
	}

	public static Date getDate(int year, int month, int day, int hour, int minute, int second) {
		Calendar c = Calendar.getInstance();
		c.set(year, month - 1, day, hour, minute, second);
		return c.getTime();
	}

	public static Date getDate(int year, int month, int day) {
		return getDate(year, month, day, 0, 0, 0);
	}

	public static Date getNewDate(Date date, long gap) {
		return new Date(date.getTime() + gap);
	}

	public static Date getNextDate(Date date, long gap) {
		return getNewDate(date, gap);
	}

	public static Date getLastDate(Date date, long gap) {
		return getNewDate(date, gap * -1);
	}

	public static int getDayPeriod(Date start, Date end) {
		long startTime = start.getTime();
		long endTime = end.getTime();
		return getDayPeriod(startTime, endTime);
	}

	public static int getDayPeriod(long start, long end) {
		int offset = TimeZone.getDefault().getRawOffset();
		start += offset;
		end += offset;
		long period = end / DAY - start / DAY;
		return (int) period;
	}

	public static boolean isLeapYear(int year) {
		if (year % 100 == 0) {
			return false;
		}
		if (year % 4 == 0 || year % 400 == 0) {
			return true;
		} else {
			return false;
		}
	}
}
